import { useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'

// 不需要登录就可以访问的路由
const publicRoutes = [
  '/login',
  '/zhuce',
  '/auth/gitee/callback'
]

export function useAuth() {
  const navigate = useNavigate()
  const location = useLocation()

  useEffect(() => {
    // 检查当前路径是否为公开路由
    const isPublicRoute = publicRoutes.some(route => 
      location.pathname === route || location.pathname.startsWith(route)
    )

    // 检查用户是否已登录（通过检查token是否存在）
    const token = localStorage.getItem('token')
    const isLoggedIn = !!token

    // 如果用户未登录且当前不是公开路由，则重定向到登录页
    if (!isLoggedIn && !isPublicRoute) {
      // 保存当前路径，登录后可以跳转回来
      localStorage.setItem('redirectPath', location.pathname)
      navigate('/login', { replace: true })
    }
  }, [location.pathname, navigate])

  return {
    isLoggedIn: !!localStorage.getItem('token')
  }
}

